<template>
  <div class="sidebar-container" ref="sidebarRef">
    <div
      class="sidebar-item"
      v-for="(item, index) in menuItems"
      :key="index"
      :class="{ active: selectedItem === index }"
      @click="handleItemClick(item, index)"
    >
      <div class="sidebar-item-icon">
        <IconFont class="icon" :name="item.icon" size="2.6042vw" />
      </div>
      <div class="sidebar-item-text">{{ item.text }}</div>
    </div>
  </div>
</template>

<script setup>
/**
 * [MODIFIED] Changed component description
 * 左侧垂直工具栏组件
 *
 * 功能：显示绘图工具和操作按钮，如折线、圆形、矩形、多边形、撤销和清除全部
 */
import { ref, onMounted, onUnmounted } from 'vue'
import { useBottomBarStore } from '@/stores/bottomBarStore.js'
import { getobjm } from '@/utils/getobjm.js'
import { ESGeoLineString, ESLocalCircle, ESGeoRectangle, ESGeoPolygon } from 'earthsdk3'
import { useTreeStore } from '@/stores/treeStore.js'
const treeStore = useTreeStore()
// 初始化状态管理和工具
const bottomBarStore = useBottomBarStore()
const objm = getobjm()

// 当前选中的导航项索引
const selectedItem = ref(null)
// [MODIFIED] Renamed ref
const sidebarRef = ref(null)
/**
 * [MODIFIED] Renamed configuration
 * 侧边栏菜单项配置
 * @type {Array<Object>} 菜单项数组
 * @property {string} text - 菜单项显示文本
 * @property {string} icon - 菜单项图标
 * @property {string} type - 菜单项类型，用于确定执行的操作
 */
const menuItems = ref([
  {
    text: '折线',
    icon: 'zx',
    type: 'line',
  },
  {
    text: '圆',
    icon: 'yuan',
    type: 'circle',
  },
  {
    text: '矩形',
    icon: 'jx',
    type: 'rectangle',
  },
  {
    text: '多边形',
    icon: 'dbx',
    type: 'polygon',
  },
  {
    text: '撤回',
    icon: 'ch',
    type: 'clear',
  },
  {
    text: '清空',
    icon: 'qk',
    type: 'clearAll',
  },
])

/**
 * 处理导航项点击事件
 * @param {Object} item - 点击的菜单项
 * @param {number} index - 菜单项的索引
 */
const handleItemClick = (item, index) => {
  // 执行相应的操作
  createVector(item)

  // 对于撤销和清除全部功能，不设置选中状态
  if (item.type === 'clear' || item.type === 'clearAll') {
    if (selectedItem.value !== null) {
      selectedItem.value = null
    }
    return
  }
  // 对于其他功能，设置当前选中的项
  selectedItem.value = index
}

/**
 * 根据菜单项类型创建相应的矢量对象
 * @param {Object} item - 菜单项对象
 */
const createVector = (item) => {
  switch (item.type) {
    case 'line':
      createESGeoLineString()
      break
    case 'circle':
      createESLocalCircle()
      break
    case 'rectangle':
      createESGeoRectangle()
      break
    case 'polygon':
      createESGeoPolygon()
      break
    case 'clear':
      clear()
      break
    case 'clearAll':
      clearAll()
      break
    default:
      console.log(`未知功能: ${item.type}`)
  }
}

// --- 绘图和清除逻辑 (无变化) ---
const createESGeoLineString = () => {
  const sceneObjectESGeoLineString = objm.createSceneObject(ESGeoLineString)
  if (!sceneObjectESGeoLineString) return
  sceneObjectESGeoLineString.stroked = true
  sceneObjectESGeoLineString.strokeWidth = 5
  sceneObjectESGeoLineString.editing = true
  sceneObjectESGeoLineString.editingChanged.disposableWeakOn(() => {
    if (sceneObjectESGeoLineString && sceneObjectESGeoLineString.editing === false) {
      const pos = sceneObjectESGeoLineString.points?.length
      const json = sceneObjectESGeoLineString.json
      objm.destroySceneObject(sceneObjectESGeoLineString)
      setTimeout(() => {
        if (pos && pos >= 2) {
          const addTree = treeStore.createSceneObjectTreeItemFromJson(json)
          bottomBarStore.createBottomBarData.push(addTree)
          if (addTree) treeStore.treeChange()
        }
      }, 300)
    }
  })
}

const createESLocalCircle = () => {
  const sceneObjectESLocalCircle = objm.createSceneObject(ESLocalCircle)
  if (!sceneObjectESLocalCircle) return
  sceneObjectESLocalCircle.editing = true
  sceneObjectESLocalCircle.editingChanged.disposableWeakOn(() => {
    if (sceneObjectESLocalCircle && sceneObjectESLocalCircle.editing === false) {
      const position = sceneObjectESLocalCircle.position
      const a = position[0] === 0 && position[1] === 0
      const json = sceneObjectESLocalCircle.json
      objm.destroySceneObject(sceneObjectESLocalCircle)
      setTimeout(() => {
        if (!a) {
          const addTree = treeStore.createSceneObjectTreeItemFromJson(json)
          bottomBarStore.createBottomBarData.push(addTree)
          if (addTree) treeStore.treeChange()
        }
      }, 300)
    }
  })
}

const createESGeoRectangle = () => {
  const sceneObjectESGeoRectangle = objm.createSceneObject(ESGeoRectangle)
  if (!sceneObjectESGeoRectangle) return
  sceneObjectESGeoRectangle.editing = true
  sceneObjectESGeoRectangle.editingChanged.disposableWeakOn(() => {
    if (sceneObjectESGeoRectangle && sceneObjectESGeoRectangle.editing === false) {
      const pos = sceneObjectESGeoRectangle.points?.length
      const json = sceneObjectESGeoRectangle.json
      objm.destroySceneObject(sceneObjectESGeoRectangle)
      setTimeout(() => {
        if (pos && pos >= 2) {
          const addTree = treeStore.createSceneObjectTreeItemFromJson(json)
          bottomBarStore.createBottomBarData.push(addTree)
          if (addTree) treeStore.treeChange()
        }
      }, 300)
    }
  })
}

const createESGeoPolygon = () => {
  const sceneObjectESGeoPolygon = objm.createSceneObject(ESGeoPolygon)
  sceneObjectESGeoPolygon.editing = true
  sceneObjectESGeoPolygon.editingChanged.disposableWeakOn(() => {
    if (sceneObjectESGeoPolygon && sceneObjectESGeoPolygon.editing === false) {
      const pos = sceneObjectESGeoPolygon.points?.length
      const json = sceneObjectESGeoPolygon.json
      objm.destroySceneObject(sceneObjectESGeoPolygon)
      setTimeout(() => {
        if (pos && pos >= 3) {
          const addTree = treeStore.createSceneObjectTreeItemFromJson(json)
          bottomBarStore.createBottomBarData.push(addTree)
          if (addTree) treeStore.treeChange()
        }
      }, 300)
    }
  })
}

const clear = () => {
  if (bottomBarStore.hasCreateBottomBarData) {
    const recently = bottomBarStore.createBottomBarData.pop()
    treeStore.destroySceneObjectTreeItem(recently)
    treeStore.treeChange()
  }
}

const clearAll = () => {
  if (!bottomBarStore.hasCreateBottomBarData) return
  bottomBarStore.createBottomBarData.forEach((item) => {
    if (item) treeStore.destroySceneObjectTreeItem(item)
  })
  treeStore.treeChange()
  bottomBarStore.createBottomBarData = []
}

/**
 * 处理全局点击事件
 * @param {Event} event - 点击事件对象
 */
const handleClickOutside = (event) => {
  if (selectedItem.value === null) return
  // [MODIFIED] Use the renamed ref
  const isClickInSidebar = sidebarRef.value && sidebarRef.value.contains(event.target)
  if (!isClickInSidebar) {
    selectedItem.value = null
  }
}

// 挂载和卸载事件监听器
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style lang="scss" scoped>
/* [MODIFIED] Renamed classes and updated styles for vertical layout */
.sidebar-container {
  position: absolute;
  z-index: 2;
  top: 8.3333vw; /* 160px -> 8.3333vw */
  right: 140px;
  /* width is now auto */
  /* height is now auto */
  background-color: rgba(0, 8, 26, 0.7);
  border-radius: 0.4167vw; /* 8px -> .4167vw */
  box-shadow: 0 0 0.5208vw /* 10px -> .5208vw */ rgba(0, 195, 255, 0.5);
  border: 0.0521vw /* 1px -> .0521vw */ solid rgba(0, 195, 255, 0.6);
  display: flex;
  flex-direction: column; /* Stacks items vertically */
  gap: 0.5208vw; /* 10px -> .5208vw */
  padding: 0.5208vw; /* 10px -> .5208vw */
  overflow: hidden;
  animation: slideInFromLeft 0.6s cubic-bezier(0.16, 1, 0.3, 1) forwards;
}

.sidebar-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 0.5208vw; /* 10px -> .5208vw */
  width: 5.2083vw; /* 100px -> 5.2083vw */
  height: 5.2083vw; /* 100px -> 5.2083vw */
  cursor: pointer;
  position: relative;
  border-radius: 0.2604vw;
  transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);

  &:hover {
    background-color: rgba(0, 195, 255, 0.2);
    .sidebar-item-icon .icon {
      scale: 0.8;
    }
  }
  &.active {
    background-color: rgba(0, 195, 255, 0.3);
    box-shadow: 0 0 0.3125vw rgba(0, 195, 255, 0.8);
  }
}

.sidebar-item-icon .icon {
  width: 2.6042vw; /* 50px -> 2.6042vw */
  height: 2.6042vw; /* 50px -> 2.6042vw */
  object-fit: contain;
  transition: all 0.5s;
}

.sidebar-item-text {
  height: 1.0417vw; /* 20px -> 1.0417vw */
  line-height: 1.0417vw; /* 20px -> 1.0417vw */
  font-size: 0.9375vw; /* 18px -> .9375vw */
  color: #fff;
}

/* [MODIFIED] New animation for sliding in from the left */
@keyframes slideInFromLeft {
  0% {
    transform: translateX(150%);
    opacity: 0;
  }
  100% {
    transform: translateX(0);
    opacity: 1;
  }
}
</style>
